from pywintypes import com_error
from win32com.client import DispatchEx
from .constants import WdSaveOptions, WdOriginalFormat, unpack
from .base import Object


# global application object
app = None


class Application(Object):
    def __init__(self, instance=None, visible=True):
        if instance is None:
            try:
                instance = DispatchEx('Word.Application')
            except:
                raise
        app = instance
        super().__init__(instance)
        self.Visible = visible

    @property
    def Visible(self):
        assert(self.Instance is not None)
        return self.Instance.Visible

    @Visible.setter
    def Visible(self, visible):
        assert(self.Instance is not None)
        self.Instance.Visible = visible

    @property
    def Documents(self):
        assert(self.Instance is not None)
        from .document import Documents
        return Documents(self.Instance.Documents)

    @property
    def ActiveDocument(self):
        assert(self.Instance is not None)
        from .document import Document
        return Document(self.Instance.ActiveDocument)

    def Quit(self,
             SaveChanges:WdSaveOptions=WdSaveOptions.wdDoNotSaveChanges,
             OriginalFormat:WdOriginalFormat=WdOriginalFormat.wdWordDocument,
             RouteDocument=True):
        if self.Instance is not None:
            try:
                kwargs = {
                    'SaveChanges': unpack(SaveChanges),
                    'OriginalFormat': unpack(OriginalFormat),
                    'RouteDocument': RouteDocument
                }
                self.Instance.Quit(**kwargs)
                self.Instance = None
            except com_error as e:
                print(f'Quit Word Error: {e}:{type(e)}')

    # def __del__(self):
    #     self.Quit()

def doc2pdf(docx, pdf=None):
    word = Application(visible=False)
    document = word.Documents.Open(docx)
    return document.ExportAsFixedFormat(pdf)


def data2docx(data, filepath=None):
    word = Application(visible=False)
    docx = word.Documents.Add()
    for item in data['Paragraphs']:
        p = docx.Paragraphs.Add()
        p.Range.InsertAfter(item.Text)
        p.Style = item.Style
    return data

# def docx2py(docx, out=None):
#     if out is None:
#         from .file import replace_ext, abspath
#         out = replace_ext(docx.FullName, '.py')
#     with open(out, mode='w', encoding='utf-8') as fd:
#         lines = ['from msoffice.word import Application\n',
#                  'app = Application()\n',
#                  'doc = app.Documents.Add()\n'
#                  ]
#         fd.writelines(lines)
#         for p in docx.Paragraphs:
#             text = p.Range.Text[:-1]
#             lines = ['p = doc.Paragraphs.Add()\n',
#                     f'p.Range.InsertAfter("{text}\\n")\n']
#             fd.writelines(lines)
#         outputPath = abspath(out) + ".docx"
#         print(f'docx2py: {outputPath}')
#         lines = [f'doc.SaveAs2(FileName="{outputPath}")']
#         fd.writelines(lines)
